package com.agu.mgt.address.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.agu.common.annotation.SysLog;
import com.agu.common.excel.Column;
import com.agu.common.excel.ExcelExport;
import com.agu.entity.address.EntAddressEntity;
import com.agu.mgt.address.service.EntAddressService;
import com.agu.mgt.sys.controller.AbstractController;
import com.agu.result.Result;
import com.agu.result.ResultGenerator;
import com.agu.utils.CompareUtils;
import com.agu.utils.JsonUtils;
import com.agu.utils.Query;
import com.agu.utils.xss.XssHttpServletRequestWrapper;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.github.pagehelper.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 通讯录
 * 
 * @author
 * @email
 * @date 2019-01-28 13:37:37
 */
@SuppressWarnings("rawtypes")
@RestController
@Api("通讯录")
@RequestMapping("entaddress")
public class EntAddressController extends AbstractController {
	@Autowired
	private EntAddressService entAddressService;

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@ApiOperation(value = "列表", notes = "说明")
	@RequiresPermissions("entaddress:list")
	public Result list(@RequestBody Map params) {

		params.put("spId", this.getSpId());

		// 查询列表数据
		Query query = new Query(params);
		Page<EntAddressEntity> page = entAddressService.queryPageList(query);
		return ResultGenerator.successPage(page);
	}

	/**
	 * 信息
	 */
	@GetMapping("/info/{addressId}")
	@ApiOperation(value = "信息", notes = "说明")
	@RequiresPermissions("entaddress:info")
	public Result info(@PathVariable("addressId") Long addressId) {

		Long spid = this.getSpId();

		EntAddressEntity entAddress = entAddressService.queryObject(addressId);

		Long spid2 = entAddress.getSpId();

		if (spid != null) {
			if (!spid.equals(spid2)) {
			 return	ResultGenerator.fail("非法操作");
			}
		}

		String mobiles = entAddress.getMobiles();

		if (StringUtils.isNotBlank(mobiles)) {

			JavaType javaType = JsonUtils.getCollectionType(ArrayList.class, String.class);

			ArrayList<String> list;
			try {
				list = JsonUtils.deserialize(mobiles, javaType);
				StringBuffer sb = new StringBuffer();

				for (String mobile : list) {
					if (sb.length() == 0) {
						sb.append(mobile);
					} else {
						sb.append(";\n");
						sb.append(mobile);
					}
				}

				entAddress.setMobilesTxt(sb.toString());

			} catch (JsonParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return ResultGenerator.successData(entAddress);
	}

	/**
	 * 保存
	 */
	@SysLog("新增通讯录")
	@PostMapping("/save")
	@ApiOperation(value = "保存", notes = "说明")
	@RequiresPermissions("entaddress:save")
	public Result save(@RequestBody EntAddressEntity entAddress) {

		entAddress.setCreateTime(new Date());
		entAddress.setCreateUserId(this.getUserId());
		entAddress.setSpId(this.getSpId());

		String mobilesTxt = entAddress.getMobilesTxt();

		Set mobilesSet = new HashSet();

		String reg = "^[1][0-9]{10}$";
		Pattern p = Pattern.compile(reg);

		if (StringUtils.isNotBlank(mobilesTxt)) {
			String[] strs = mobilesTxt.split(";");
			for (String str : strs) {
				if (str != null) {
					if (Pattern.matches(reg, str.trim())) {
						mobilesSet.add(str.trim());
					}
				}
			}
			entAddress.setMobilesNum(mobilesSet.size());
			entAddress.setMobiles(JsonUtils.toJson(mobilesSet));
		} else {
			entAddress.setMobilesNum(0);
		}

		entAddressService.save(entAddress);

		// 处理日志
		Map<String, String> cmap = new HashMap<String, String>();
		cmap.put("addressName", "通讯录名称");
		cmap.put("spId", "spID");
		cmap.put("mobiles", "手机号码");
		String remark = CompareUtils.getObjectRemark(entAddress, cmap);
		return ResultGenerator.success("保存成功").setRemark(remark);
	}

	/**
	 * 修改
	 */
	@SysLog("修改通讯录")
	@PostMapping("/update")
	@ApiOperation(value = "修改", notes = "说明")
	@RequiresPermissions("entaddress:update")
	public Result update(@RequestBody EntAddressEntity entAddress) {

		Long spid = entAddress.getSpId();

		if (spid == null) {
			return ResultGenerator.fail("数据错误");
		}

		if(this.getSpId()!=null)
		{
			if (this.getSpId().longValue() != spid.longValue()) {
				return ResultGenerator.fail("非法操作");
			}
		}

		String mobilesTxt = entAddress.getMobilesTxt();

		Set mobilesSet = new HashSet();

		String reg = "^[1][0-9]{10}$";
		Pattern p = Pattern.compile(reg);

		if (StringUtils.isNotBlank(mobilesTxt)) {
			String[] strs = mobilesTxt.split(";");
			for (String str : strs) {
				if (str != null) {
					if (Pattern.matches(reg, str.trim())) {
						mobilesSet.add(str.trim());
					}
				}
			}
			entAddress.setMobilesNum(mobilesSet.size());
			entAddress.setMobiles(JsonUtils.toJson(mobilesSet));
		} else {
			entAddress.setMobilesNum(0);
		}

		EntAddressEntity entAddress1 = entAddressService.queryObject(entAddress.getAddressId());

		entAddressService.update(entAddress);

		// 处理日志
		Map<String, String> cmap = new HashMap<String, String>();

		cmap.put("addressName", "通讯录名称");
		cmap.put("spId", "spID");
		cmap.put("mobiles", "手机号码");

		String remark = CompareUtils.getTwoObjectRemark(entAddress1, entAddress, cmap);

		return ResultGenerator.success("修改成功").setRemark(remark);
	}

	/**
	 * 删除
	 */
	@SysLog("删除通讯录")
	@GetMapping("/delete/{addressId}")
	@ApiOperation(value = "删除", notes = "说明")
	@RequiresPermissions("entaddress:delete")
	public Result delete(@PathVariable("addressId") Long addressId) {

		if (addressId == null) {
			return ResultGenerator.fail("缺少参数");
		}

		EntAddressEntity entAddress = entAddressService.queryObject(addressId);

		entAddressService.delete(addressId);

		// 处理日志
		Map<String, String> cmap = new HashMap<String, String>();
		cmap.put("addressName", "通讯录名称");
		cmap.put("spId", "spID");
		cmap.put("mobiles", "手机号码");
		String remark = CompareUtils.getObjectRemark(entAddress, cmap);
		return ResultGenerator.success("删除成功").setRemark(remark);
	}

	/**
	 * 批量删除
	 */
	@SysLog("批量删除通讯录")
	@PostMapping("/deletes")
	@ApiOperation(value = "删除", notes = "说明")
	@RequiresPermissions("entaddress:delete")
	public Result deletes(@RequestBody Long[] addressIds) {

		entAddressService.deleteBatch(addressIds);

		return ResultGenerator.success("删除成功");
	}

	@RequestMapping("/download")
	@ApiOperation(value = "下载", notes = "说明")
	@RequiresPermissions("entaddress:list")
	public void download(HttpServletRequest request, HttpServletResponse response) {

		HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request);

		String query = orgRequest.getParameter("query");

		HashMap querymap = JSON.parseObject(query, HashMap.class);

		List<EntAddressEntity> list = entAddressService.queryList(querymap);

		if (list != null && list.size() > 0) {
			Map map = new HashMap();

			List<Column> clist = new ArrayList();
			Column cloumn = null;

			cloumn = new Column("通讯录ID", "addressId", 1);
			clist.add(cloumn);
			cloumn = new Column("通讯录名称", "addressName", 1);
			clist.add(cloumn);
			cloumn = new Column("spID", "spId", 1);
			clist.add(cloumn);
			cloumn = new Column("手机号码数", "mobilesNum", 1);
			clist.add(cloumn);
			cloumn = new Column("手机号码", "mobiles", 1);
			clist.add(cloumn);
			cloumn = new Column("创建人", "createUserId", 1);
			clist.add(cloumn);
			cloumn = new Column("创建时间", "createTime", 1);
			clist.add(cloumn);
			try {
				ExcelExport export = exportList(list, clist, map);
				if (export != null) {
					this.downExcel(export, response);
					// this.downzip(export, response);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
